﻿using EmailClient.Model;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace EmailClient.ViewModel
{
    class AccountViewModel
    {
        public static async Task<ObservableCollection<EmailAccount>> GetList()
        {
            var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
            using (var db = dbFactory.Open())
            {
                return new ObservableCollection<EmailAccount>(await db.SelectAsync<EmailAccount>());                
            }             
        }

        public static async Task<string> GetStatus(int accountId)
        {
            var result = "";
            var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
            using (var db = dbFactory.Open())
            {
                var l = await db.SelectAsync<EmailAccount>(x => x.Id == accountId);
                if (l.Count > 0) result = l[0].MailType;
            }
            return result;
        }  

        public static async Task<string> Insert(EmailAccount item)
        {
            var result = "success";            
            try
            {
                var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
                using (var db = dbFactory.Open())
                {
                    await db.InsertAsync(item);
                }                
            }
            catch (Exception e) { result = e.Message; }

            return result;
        }

        public static async Task<string> Update(EmailAccount item)
        {
            var result = "success";
            try
            {
                var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
                using (var db = dbFactory.Open())
                {
                    await db.UpdateAsync(item);
                }
            }
            catch (Exception e) { result = e.Message; }

            return result;
        }

        public static async Task<string> Delete(EmailAccount item)
        {
            var result = "success";
            try
            {
                var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
                using (var db = dbFactory.Open())
                {                   
                    await db.DeleteAsync(item);
                }
            }
            catch (Exception e) { result = e.Message; }

            return result;
        }
    }
}
